package com.dengxiujun.simpletomcat.response;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author dengxiujun
 * @date 2021-04-26
 **/
public class HttpResponse {

    private OutputStream outputStream = null;
    private SocketChannel socketChannel = null;

    public HttpResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public HttpResponse(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public void write(String content) throws IOException {
        StringBuilder response = new StringBuilder();
        response.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: text/html;charset=UTF-8\n")
                .append("\r\n")
                .append("<html>")
                .append("<body>")
                .append(content)
                .append("</body>")
                .append("</html>")
                .append("\r\n");
        if (socketChannel != null) {
            socketChannel.write(ByteBuffer.wrap(response.toString().getBytes(StandardCharsets.UTF_8)));
        } else {
            this.outputStream.write(response.toString().getBytes(StandardCharsets.UTF_8));
        }
        
    }

    public void write(byte[] content) throws IOException {
        StringBuilder response = new StringBuilder();
        response.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: image/x-icon\n")
                .append("\r\n");
        if (socketChannel != null) {
            socketChannel.write(ByteBuffer.wrap(response.toString().getBytes(StandardCharsets.UTF_8)));
            socketChannel.write(ByteBuffer.wrap(content));
        } else {
            this.outputStream.write(response.toString().getBytes(StandardCharsets.UTF_8));
            this.outputStream.write(content);
        }
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

}
